from celery.worker.state import requests
from flask import Blueprint, jsonify, current_app, send_file, request, redirect
from flask_restful import Api, Resource,reqparse

from utils import myjwt
from utils.smscode import sms_code
from utils.myredis import r
from models.user.user import User, db, SfLogin
from captcha.image import ImageCaptcha
login_bp = Blueprint('login_bp', __name__, url_prefix='/')
api = Api(login_bp)
import random
import time
import jwt
import json
# 图片验证码
class ImgView(Resource):
    def get(self,uuid):
        img = ImageCaptcha()
        code = random.randint(1000,9999)
        code1 = str(code)
        img_png = img.generate(code1)
        r.ser_add(uuid,code1,3600)
        return send_file(img_png,mimetype="png")
api.add_resource(ImgView,'/img/<uuid>')

# 短信验证码
class SendSmsCode(Resource):
    def post(self):
        req = reqparse.RequestParser()
        req.add_argument('uuid')
        req.add_argument('mobile')
        req.add_argument('piccode')
        args = req.parse_args()
        print(args['piccode'])

        # 从redis中取出来 图片验证码
        value = r.str_get('uuid='+ args['uuid'])
        if value:
            if args['piccode'] == value.decode():
                # 验证一分钟内只能发一次
                mcode = r.str_get(args['mobile'])
                if mcode:
                    return jsonify({'code':10012,'msg':'一分钟内不能重复发送'})
                # 调用短信平台
                # 生成5位随机数
                smscode = str(random.randint(1000, 9999))
                flag = sms_code(args['mobile'], smscode)
                if flag:
                    # 手机验证码存入redis
                    r.ser_add(args['mobile'],smscode,60)
                    # 删除图片验证码
                    r.del_str(args['uuid'])
                    # 返回结果
                    return jsonify({'code':200,'msg':'发送成功'})
                else:
                    return jsonify({'code': 10013, 'msg': '发送验证码失败'})
            else:
                return jsonify({'code':10011,'msg':'图片验证码错误'})
        else:
            return jsonify({'code': 10010, 'msg': '图片验证码不存在'})
api.add_resource(SendSmsCode,'/sendSmsCode')
# 登录接口
class LoginView(Resource):
    def post(self):
        req = reqparse.RequestParser()
        req.add_argument('smscode')
        req.add_argument('mobile')
        args = req.parse_args()
        # 判断数据是否存在
        if not all([args['smscode'],args['mobile']]):
            return jsonify({
                'code':400,
                'msg':'数据不完整'
            })
        # 从redis中取出  验证码
        code = r.str_get(args['mobile'])
        if code:
            print(code,55555)
            # 判断验证码是否相同
            if int(code) == int(args['smscode']):
                user = User.query.filter(User.mobile == args['mobile']).first()
                print(user,111111)
                # 如果相同 删除验证码（为了节约内存）
                # 否则  存入到用户表中
                if user:
                    r.del_str(args['mobile'])
                else:
                    u = User(mobile=args['mobile'],nikename=args['mobile'])
                    db.session.add(u)
                    db.session.commit()
                    user = User.query.filter(User.mobile == args['mobile']).first()
                # 生成一个token  key加盐
                # 返回token给前端  用户id也返回过去
                key = current_app.config.get('SECRET_KEY')
                token = jwt.encode({
                    'user_id':user.id,
                    'exp': int(time.time()) + 180
                },key,algorithm='HS256')
                return jsonify({
                    'code':200,
                    'msg':'登录成功',
                    'token':token,
                    'user_id':user.id
                })
            else:
                return jsonify({'code':400,'msg':'验证码错误'})
        else:
            return jsonify({'code':400,'msg':'验证码已过期'})
api.add_resource(LoginView,'/login')
# 微博登录

# 获取weibo地址
class getwburl(Resource):
    def get(self):
        client_id = "3674019597"
        redirect_uri = "http://127.0.0.1:8000/user/weiboCallback/"
        url = "https://api.weibo.com/oauth2/authorize?client_id=%s&redirect_uri=%s&response_type=code" % (
            client_id, redirect_uri)
        return jsonify({"code":200,"url":url})
api.add_resource(getwburl,'/sf_login')

class WeiBoHeadler(Resource):
    def get(self):
        code = request.args.get("code")
        data = {"client_id": '3674019597',
                "client_secret": "7ae99bc0d54ead29fc8d1b9fabd78587",
                "grant_type": "authorization_code",
                'redirect_uri': 'http://127.0.0.1:8000/user/weiboCallback/', 'code': code}
        res1 = requests.post('https://api.weibo.com/oauth2/access_token', data=data)
        mes = json.loads(res1.text)
        # 获取微博平台的用户信息
        uid = mes["uid"]
        token = mes["access_token"]
        # 查询此id是否存在
        sql = "select user.id from sf_login inner join user on user.id=sf_login.userid where sf_login.uid='%s'"%(uid)
        user = db.session.execute(sql)
        if user:
            for i in user:
                # 生成token，跳转到vue中转页
                token = myjwt.jwt_encode(data={"data":{"uid":i[0],"exp":int(time.time())}})
                return redirect("http://localhost:8080/#/updatetoken?token="+token+"&userid="+str(i[0]))
        return redirect("http://localhost:8080/#/wbdl?uid="+str(uid)+"&token="+str(token))

    def post(self):
        # 接收参数
        data = json.loads(request.data)
        mobile = data["mobile"]
        uid = data["uid"]
        token = data["token"]
        # 加入用户表
        user = User.query.filter(User.mobile == mobile).first()
        if not user:
            # 添加
            u = User(mobile=mobile, nikename=mobile)
            db.session.add(u)
            db.session.commit()
            # 获取用户信息
            user = User.query.filter(User.mobile == mobile).first()
        sfuser = SfLogin(userid=user.id, webfrom="wb", uid=uid, token=token)
        print("sss", sfuser)
        db.session.add(sfuser)
        db.session.commit()
        data = {"data": user.id, "exp": int(time.time())}
        token = myjwt.jwt_encode(data)
        return redirect("http://localhost:8080/#/updatetoken?token=" + token + "&userid=" + str(user.id))

api.add_resource(WeiBoHeadler,"/user/weiboCallback/")





